package com.market.cash.ui.fragment

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import com.market.cash.R
import com.market.cash.databinding.CashPinStatusProcessBinding
import com.market.cash.pro.ProFragment
import com.market.cash.ui.activity.KefuActivity
import com.market.cash.ui.activity.PinStatusActivity
import com.market.cash.utils.event.CashRootEventHelper.addCashRootRequestEventAction
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.thread.TimingThread
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/25 17:04
 * @Annotation：支付结果处理中
 */
class PinProcessFragment(): ProFragment(), TimingThread.ITimingThreadListener {
    lateinit var binding: CashPinStatusProcessBinding
    private var orderData: JSONObject? = null
    private var act: PinStatusActivity? = null
    //倒计时
    private var countdown = 30
    private var timeThread: TimingThread? = null

    constructor(act: PinStatusActivity, data: JSONObject): this(){
        this.act = act
        this.orderData = data
    }
    override fun getCashRootRootView(inflater: LayoutInflater): View {
        binding = CashPinStatusProcessBinding.inflate(inflater)
        return binding.root
    }

    override fun initCashRootView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#F8F8F8"))
        setCashRootTitleBarVisibility(View.VISIBLE)
        setCashRootBackBtnRes(R.mipmap.cash_back_black)
        setCashRootTextTitle(getString(R.string.loan_payment_status_title))
        setCashRootRightBtnRes(R.mipmap.cash_kefu_black)
        setCashRootTitleBarColor(Color.parseColor("#FFFFFF"))
    }

    override fun initCashRootListener() {
        //客服
        rootViewBinding.imgKefu.setOnClickListener {
            if (act != null){
                KefuActivity.start(requireContext(),"PIN PaymentProcess Page",act!!.loadPName(),act!!.loadPToken())
            }
            addCashRootRequestEventAction(CashRootEventType.CLICK.CASHROOT_CLICK_CUSTOMER,"PIN PaymentProcess Page")
        }
        //刷新
        binding.refreshLayout.setOnClickListener {
            if (orderData != null){
                addCashRootRequestEventAction(CashRootEventType.CLICK.CASHROOT_CLICK_LOAN_PAYMENT_PROCESS_PAYMENT_UPDATE,"TransactionId：${orderData!!.optString("transactionId")}")
            }
            if (act != null){
                //再次调用查询状态接口
                act!!.presenter!!.loadCashRootPaymentStatusAction()
            }
        }

        //再次还款
        binding.btnPaymentAgain.setOnClickListener {
            if (orderData != null){
                addCashRootRequestEventAction(CashRootEventType.CLICK.CASHROOT_CLICK_LOAN_PAYMENT_PROCESS_PAYMENT_AGAIN,"TransactionId：${orderData!!.optString("transactionId")}")
            }
            if (act != null){
                act!!.presenter!!.loadCashRootOrderPayLinkAction()
            }
        }
    }

    override fun initCashRootData() {
        if (orderData != null){
            refreshData(this.orderData!!)
        }
        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 刷新数据
     */
    fun refreshData(data: JSONObject){
        this.orderData = data
        val realRepayAmount = data.optString("realRepayAmount","")
        binding.textAmount.text = realRepayAmount
        binding.textProduct.text = data.optString("product","")

        binding.txtProcessedReason.text = String.format(getString(R.string.loan_payment_status_processed_reason1),realRepayAmount)

        countdown = 0
        showCashRootPaymentStatus()
        //是否开启倒计时
        if (data.optBoolean("isStartCountdown",true)){
            startTimeThread()
        }
    }

    /**
     * 启动倒计时
     */
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        countdown = 30
        showCashRootPaymentStatus()
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread!!.setThreadDelayMillis(1000)
            timeThread!!.setLoadListener(this)
        }
        timeThread!!.startThread()
    }

    /**
     * 倒计时
     */
    override fun onLoading() {
        if (countdown <= 0) {
            countdown = 30
            timeThread!!.stopThread()

            if (act != null){
                //倒计时结束，自动调一次状态查询接口
                act!!.presenter!!.loadCashRootPaymentStatusAction(false)
            }
            return
        }
        countdown--
        showCashRootPaymentStatus()
    }

    /**
     * 设置按钮状态
     */
    private fun showCashRootPaymentStatus(){
        if (countdown <= 0){
            binding.btnPaymentAgain.isEnabled = true
            binding.btnPaymentAgain.isClickable = true
            binding.btnPaymentAgain.text = String.format(getString(R.string.loan_payment_status_make_payment_again),"")
        } else {
            binding.btnPaymentAgain.isEnabled = false
            binding.btnPaymentAgain.isClickable = false
            binding.btnPaymentAgain.text = String.format(getString(R.string.loan_payment_status_make_payment_again),"(${countdown}s)")
        }
    }

    override fun onStart() {
        super.onStart()
        if (act != null){
            addCashRootRequestEventAction(CashRootEventType.PAGE.CASHROOT_PAGE_LOAN_PIN_REPAYMENT_PROCESS_START,act!!.loadPName())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (act != null){
            addCashRootRequestEventAction(CashRootEventType.PAGE.CASHROOT_PAGE_LOAN_PIN_REPAYMENT_PROCESS_END,act!!.loadPName())
        }
        if (timeThread != null) {
            timeThread!!.stopThread()
            timeThread = null
        }
    }
}